package com.cheney.weiboo.view;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.CharacterStyle;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.cheney.weiboo.R;
import com.cheney.weiboo.domain.Users;
import com.cheney.weiboo.service.UserService;
import com.cheney.weiboo.utils.AsyncImageLoader;
import com.cheney.weiboo.utils.TimeUtil;
import com.cheney.weiboo.utils.AsyncImageLoader.ImageCallback;
import com.mime.qweibo.examples.MyWeiboSync;

public class WeiBoDetailActivity extends Activity{

	private ImageView detailHeadIcon;
	private TextView nickView;
	private Button toInfo;
	private UserService userService;
	private List<Users> userList;
	private Users users;
	private MyWeiboSync weibo;
	private String weiboId;
	private String returnJsonStr;
	private DetailHandler handler;
	private JSONObject jsonObject;
	private AsyncImageLoader asyncImageLoader;
	private TextView show_count_mcount;
	private TextView show_origtext;
	private ExecutorService executorService;
	private TextView detail_at;
	private TextView show_time;
	private TextView show_from;
	private ImageView show_delete;
	private ImageView show_image;
	private Button detail_toinfo;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.weibo_detail);
		setView();
		setListener();
		
		Intent intent = getIntent();
		weiboId = intent.getStringExtra("id");
		userService = new UserService(this);
		userList = userService.getUserList(false);
		weibo = new MyWeiboSync();
		asyncImageLoader = new AsyncImageLoader();
		
		SharedPreferences preferences = getSharedPreferences("default_users", Context.MODE_PRIVATE);
		String nick = preferences.getString("user_default_nick", "");
		if(nick!=null){
			users = userService.getUserByName(nick, userList);
		}
		
		weibo.setAccessTokenKey(users.getToken());
		weibo.setAccessTokenSecrect(users.getTokenSecret());
		
		handler = new DetailHandler();
		executorService.submit(new GetDetailThread());
	}
	
	
	//设置view
	public void setView(){
		detailHeadIcon = (ImageView)findViewById(R.id.detail_head_pic);
		nickView = (TextView)findViewById(R.id.detail_nick);
		toInfo = (Button)findViewById(R.id.detail_toinfo);
		show_count_mcount = (TextView)findViewById(R.id.show_count_mcount);
		show_origtext = (TextView)findViewById(R.id.show_origtext);
		executorService = Executors.newFixedThreadPool(3);
		detail_at = (TextView)findViewById(R.id.detail_at);
		show_time = (TextView)findViewById(R.id.show_time);
		show_from = (TextView)findViewById(R.id.show_from);
		show_delete = (ImageView)findViewById(R.id.show_delete);
		show_image = (ImageView)findViewById(R.id.show_image);
		detail_toinfo = (Button)findViewById(R.id.detail_toinfo);
	}
	
	//设置listener
	public void setListener(){
		detail_toinfo.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(WeiBoDetailActivity.this,UserInfoActivity.class);
				try {
					intent.putExtra("name", jsonObject.getString("name"));
					intent.putExtra("nick", jsonObject.getString("nick"));
					intent.putExtra("origtext", jsonObject.getString("origtext"));
					intent.putExtra("time", TimeUtil.getStandardTime(jsonObject.getLong("timestamp")));
					startActivity(intent);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	//创建线程
	class GetDetailThread extends Thread{
		@Override
		public void run() {
			returnJsonStr = weibo.getWeiboDetail(weibo.getAccessTokenKey(), weibo.getAccessTokenSecrect(), weiboId);
			Message message = handler.obtainMessage();
			handler.sendMessage(message);
		}
	}
	
	//创建Handler
	class DetailHandler extends Handler{
		@Override
		public void handleMessage(Message msg) {
			Drawable cachedImage;
			try {
				jsonObject = new JSONObject(returnJsonStr).getJSONObject("data");
				
				cachedImage = asyncImageLoader.loadDrawable(jsonObject.getString("head")+"/100", detailHeadIcon, new ImageCallback(){
					@Override
					public void imageLoaded(Drawable imageDrawable,
							ImageView imageView, String imageUrl) {
						imageView.setImageDrawable(imageDrawable);
					}
				});
				if(cachedImage==null){
					detailHeadIcon.setImageResource(R.drawable.icon);
				}else {
					detailHeadIcon.setImageDrawable(cachedImage);
				}
				String count_menu = "转播和点评("+(jsonObject.getInt("count")+jsonObject.getInt("mcount"))+")";
				SpannableStringBuilder underline = new SpannableStringBuilder(count_menu);
				CharacterStyle span = new UnderlineSpan();
				underline.setSpan(span, 0, count_menu.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				show_count_mcount.setText(underline);
				
				nickView.setText(jsonObject.getString("nick"));
				show_origtext.setText(jsonObject.getString("origtext"));
				detail_at.setText("@"+jsonObject.getString("name"));
				show_time.setText(TimeUtil.getStandardTime(jsonObject.getLong("timestamp")));
				show_from.setText("来自"+jsonObject.getString("from"));
				
				if(jsonObject.getString("nick").equals(users.getUserName())){
					show_delete.setVisibility(View.VISIBLE);
				}
				JSONArray imageArray = jsonObject.optJSONArray("image");
				if(imageArray!=null&&imageArray.length()>0){
					String imageUrl = imageArray.optString(0)+"/460";
					Drawable drawable = asyncImageLoader.loadDrawable(imageUrl, show_image, new ImageCallback(){
						@Override
						public void imageLoaded(Drawable imageDrawable,
								ImageView imageView, String imageUrl) {
							imageView.setImageDrawable(imageDrawable);
						}
					});
					show_image.setVisibility(View.VISIBLE);
				}
				
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}
}
